﻿using System;
using System.Collections.Generic;
using System.Linq;
using Autodesk.Revit.DB;
using Autodesk.Revit.DB.ExtensibleStorage;

namespace YArchitech.HVAC
{
	public static class AssociationMarkInfo
	{
		public static void WriteMarkInfoToElement(Element group, IDictionary<string, string> dic)
		{
			Schema schema = Schema.Lookup(new Guid("BF40CAC3-E9A0-4C34-ABC8-784B55A36212"));
			if (schema == null)
			{
				SchemaBuilder schemaBuilder = new SchemaBuilder(new Guid("BF40CAC3-E9A0-4C34-ABC8-784B55A36212"));
				schemaBuilder.SetReadAccessLevel((AccessLevel)1);
				schemaBuilder.SetWriteAccessLevel((AccessLevel)1);
				schemaBuilder.SetVendorId("ADSK");
				schemaBuilder.AddMapField("filterMarkInfo", typeof(string), typeof(string));
				schemaBuilder.SetSchemaName("FilterMarkInfos");
				schema = schemaBuilder.Finish();
			}
			Entity entity = new Entity(schema);
			Field field = schema.GetField("filterMarkInfo");
			entity.Set<IDictionary<string, string>>(field, dic);
			group.SetEntity(entity);
		}

		public static void WriteMarkInfoToElement(Element ele, MarkType markType)
		{
			AssociationMarkInfo.WriteMarkInfoToElement(ele, new Dictionary<string, string>
			{
				{
					"typeName",
					markType.ToString()
				}
			});
		}

		public static IDictionary<string, string> GetMarkInfoFromElement(Element group)
		{
			Schema schema = Schema.Lookup(new Guid("BF40CAC3-E9A0-4C34-ABC8-784B55A36212"));
			if (schema == null)
			{
				SchemaBuilder schemaBuilder = new SchemaBuilder(new Guid("BF40CAC3-E9A0-4C34-ABC8-784B55A36212"));
				schemaBuilder.SetReadAccessLevel((AccessLevel)1);
				schemaBuilder.SetWriteAccessLevel((AccessLevel)1);
				schemaBuilder.SetVendorId("ADSK");
				schemaBuilder.AddMapField("filterMarkInfo", typeof(string), typeof(string));
				schemaBuilder.SetSchemaName("FilterMarkInfos");
				schema = schemaBuilder.Finish();
			}
			Entity entity = group.GetEntity(schema);
			if (!entity.IsValid())
			{
				return null;
			}
			return entity.Get<IDictionary<string, string>>(schema.GetField("filterMarkInfo"));
		}

		public static bool IsRightMarkType(Element group, string type)
		{
			IDictionary<string, string> markInfoFromElement = AssociationMarkInfo.GetMarkInfoFromElement(group);
			if (markInfoFromElement == null)
			{
				return false;
			}
			return markInfoFromElement.FirstOrDefault((KeyValuePair<string, string> q) => q.Key == "typeName").Value == type;
		}
	}
}
